package com.ruoyi.tb.lmt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.tb.lmt.domain.vo.MessageCountVo;
import com.ruoyi.tb.lmt.domain.vo.TbRepairplanlistApprovedVo;
import com.ruoyi.tb.lmt.domain.vo.TbRequestVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.tb.lmt.domain.bo.TbMessageNoticeBo;
import com.ruoyi.tb.lmt.domain.vo.TbMessageNoticeVo;
import com.ruoyi.tb.lmt.domain.TbMessageNotice;
import com.ruoyi.tb.lmt.mapper.TbMessageNoticeMapper;
import com.ruoyi.tb.lmt.service.ITbMessageNoticeService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 消息通知Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-18
 */
@RequiredArgsConstructor
@Service
public class TbMessageNoticeServiceImpl implements ITbMessageNoticeService {

    private final TbMessageNoticeMapper baseMapper;

    @Autowired
    private TbMessageNoticeMapper tbMessageNoticeMapper;

    @Autowired
    private ISysRoleService iSysRoleService;

    /**
     * 查询消息通知
     */
    @Override
    public TbMessageNoticeVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询消息通知列表
     */
    @Override
    public TableDataInfo<TbMessageNoticeVo> queryPageList(TbMessageNoticeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TbMessageNotice> lqw = buildQueryWrapper(bo);
        Page<TbMessageNoticeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询消息通知列表
     */
    @Override
    public List<TbMessageNoticeVo> queryList(TbMessageNoticeBo bo) {
        LambdaQueryWrapper<TbMessageNotice> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbMessageNotice> buildQueryWrapper(TbMessageNoticeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TbMessageNotice> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLmtType()), TbMessageNotice::getLmtType, bo.getLmtType());
        lqw.eq(StringUtils.isNotBlank(bo.getLmtNumber()), TbMessageNotice::getLmtNumber, bo.getLmtNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getMessageTitle()), TbMessageNotice::getMessageTitle, bo.getMessageTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getMessageType()), TbMessageNotice::getMessageType, bo.getMessageType());
        lqw.like(StringUtils.isNotBlank(bo.getMessageName()), TbMessageNotice::getMessageName, bo.getMessageName());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkerTeam()), TbMessageNotice::getWorkerTeam, bo.getWorkerTeam());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TbMessageNotice::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkGroup()), TbMessageNotice::getWorkGroup, bo.getWorkGroup());
        lqw.eq(bo.getWorkGroupId() != null, TbMessageNotice::getWorkGroupId, bo.getWorkGroupId());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkUser()), TbMessageNotice::getWorkUser, bo.getWorkUser());
        lqw.eq(bo.getWorkTime() != null, TbMessageNotice::getWorkTime, bo.getWorkTime());
        lqw.eq(bo.getCreateTime() != null, TbMessageNotice::getCreateTime, bo.getCreateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), TbMessageNotice::getCreateBy, bo.getCreateBy());
        lqw.eq(bo.getUpdateTime() != null, TbMessageNotice::getUpdateTime, bo.getUpdateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdateBy()), TbMessageNotice::getUpdateBy, bo.getUpdateBy());
        lqw.eq(StringUtils.isNotBlank(bo.getTaskUrl()), TbMessageNotice::getTaskUrl, bo.getTaskUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getMessageNeed()), TbMessageNotice::getMessageNeed, bo.getMessageNeed());
        lqw.eq(bo.getMessageId() != null, TbMessageNotice::getMessageId, bo.getMessageId());
        return lqw;
    }

    /**
     * 新增消息通知
     */
    @Override
    public Boolean insertByBo(TbMessageNoticeBo bo) {
        TbMessageNotice add = BeanUtil.toBean(bo, TbMessageNotice.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改消息通知
     */
    @Override
    public Boolean updateByBo(TbMessageNoticeBo bo) {
        TbMessageNotice update = BeanUtil.toBean(bo, TbMessageNotice.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TbMessageNotice entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除消息通知
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<TbMessageNoticeVo> selectMessage(String messageType, String workGroup, String status, Date startTime, Date endTime, PageQuery pageQuery) {

        //获取当前登录用户
        String username = LoginHelper.getLoginUser().getUsername();


        //List<TbMessageNoticeVo> result = tbMessageNoticeMapper.selectMessage(username,messageType, workGroup, status, startTime, endTime);

        // 检查当前用户的角色
        boolean isAdmin = isAdmin(username); // 是否为管理员
        boolean isEquipmentDept = isEquipmentDept(username); // 是否为设备科人员
        boolean isAcceptanceRoom = isAcceptanceRoom(username); // 是否为验收室
        boolean isDeputyDirector = isDeputyDirector(username); // 是否为车间副主任
        boolean isInspection = isInspection(username); //巡检组

        // 查询符合条件的大部件申请列表
        List<TbMessageNoticeVo> result = null;

        if (isAdmin) {
            // 管理员可以看到所有申请列表
            result = tbMessageNoticeMapper.selectMessageByAdmin(username,messageType, workGroup, status, startTime, endTime);
        } else if (isEquipmentDept) {
            // 设备科人员可以看到所有申请列表
            result = tbMessageNoticeMapper.selectMessageByEquipmentDept(username,messageType, workGroup, status, startTime, endTime);
        } else if (isAcceptanceRoom) {
            // 验收室可以看到所有申请列表
            result = tbMessageNoticeMapper.selectMessageByAcceptanceRoom(username,messageType, workGroup, status, startTime, endTime);
        } else if (isDeputyDirector) {
            // 验收室可以看到所有申请列表
            result = tbMessageNoticeMapper.selectMessageByDeputyDirector(username,messageType, workGroup, status, startTime, endTime);
        }else if (isInspection) {
            // 验收室可以看到所有申请列表
            result = tbMessageNoticeMapper.selectMessageByInspection(username,messageType, workGroup, status, startTime, endTime);
        } else {
            // 其他用户只能看到自己提交的申请列表
            result = tbMessageNoticeMapper.selectMessage(username,messageType, workGroup, status, startTime, endTime);
        }

        //
        if (pageQuery.getPageSize()!= null && pageQuery.getPageNum()!= null) {
            List<TbMessageNoticeVo> page = ListUtil.page(pageQuery.getPageNum() - 1, pageQuery.getPageSize(), result);
            TableDataInfo res = new TableDataInfo<>(page, result.size());
            return res;
        } else {
            return TableDataInfo.build(result);
        }
    }

    public boolean isInspection(String username) {
        // 根据用户名获取用户的角色信息
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 判断用户是否属于巡检组
        for (SysRole role : userRoles) {
            if ("inspectionTeam".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }

    public boolean isAdmin(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有管理员角色
        for (SysRole role : userRoles) {
            if ("admin".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }

    public boolean isEquipmentDept(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有设备科的角色标识
        for (SysRole role : userRoles) {
            if ("equipmentDept".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }


    public boolean isDeputyDirector(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有车间副主任的角色标识
        for (SysRole role : userRoles) {
            if ("deputyDirector".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }

    public boolean isAcceptanceRoom(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有验收室的角色标识
        for (SysRole role : userRoles) {
            if ("acceptanceRoom".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }
    @Override
    public TbMessageNoticeVo selectById(Long messageId) {
        return tbMessageNoticeMapper.selectMeById(messageId);
    }

    @Override
    public MessageCountVo selectAcceptCount() {
        //获取当前登录用户
        String username = LoginHelper.getLoginUser().getUsername();
        if (isAdmin(username)) {
            return tbMessageNoticeMapper.selectAcceptCountByadmin();
        } else if (isDeputyDirector(username)) {
            return tbMessageNoticeMapper.selectAcceptCountByDeputyDirector(username);
        } else if (isAcceptanceRoom(username)) {
            return tbMessageNoticeMapper.selectAcceptCountByAcceptanceRoom(username);
        } else if (isEquipmentDept(username)) {
            return tbMessageNoticeMapper.selectAcceptCountByEquipmentDepartment(username);
        } else if (isInspection(username)) {
            return tbMessageNoticeMapper.selectAcceptCountByInspection(username);
        }else {
            return tbMessageNoticeMapper.selectAcceptCount(username);
        }

    }

    @Override
    public String getDeputyDirector(Long workGroupId) {
        return tbMessageNoticeMapper.selectDeputyDirector(workGroupId);
    }

    @Override
    public String getCaptain(Long workGroupId) {
        return tbMessageNoticeMapper.selectCaptain(workGroupId);
    }

    @Override
    public String getEquipmentDepartment() {
        return tbMessageNoticeMapper.selectEquipmentDepartment();
    }

    @Override
    public String getAcceptanceRoom() {
        return tbMessageNoticeMapper.selectAcceptanceRoom();
    }

    @Override
    public String getInspection() {
        return tbMessageNoticeMapper.selectInspection();
    }
}
